package cn.gdcp.saxtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.StringReader;

import javax.xml.parsers.SAXParserFactory;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SaxActivity extends AppCompatActivity {

    Button saxGetXmlBtn;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sax);
        saxGetXmlBtn=findViewById(R.id.sax_getXml_button);
        saxGetXmlBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                new Thread(new Runnable() {
                    public void run() {
                        try{
                        OkHttpClient client=new OkHttpClient();
                        Request request=new  Request.Builder().url("http://192.168.43.34:8080/ch1_ex1_news/get_data.xml").build();
                        Response response=client.newCall(request).execute();
                        getXml(response.body().string());

                        }catch (Exception e)
                        {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }
        });

    }

    private void getXml(String s) {
        try{
        SAXParserFactory factory=SAXParserFactory.newInstance();
        XMLReader xmlReader=factory.newSAXParser().getXMLReader();
         ContentHandler handler=new ContentHandler();
         xmlReader.setContentHandler(handler);
         xmlReader.parse(new InputSource(new StringReader(s)));
        }
        catch (Exception e){
            e.printStackTrace();
        }




    }
}
